<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="visible"
    :width="screenWidth"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog"
  >
    <el-form ref="addFormRef" v-loading="loading" :model="formData" :rules="rules" size="" label-width="100px">
      <el-row justify="start" class="d_left">
        <el-col :span="itemSpan" class="">
          <el-form-item label="通知标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入通知标题" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan" class="">
          <el-form-item label="通知内容" prop="content">
            <editor v-if="formData.id != 0" :data="formData" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan" class="">
          <el-form-item label="相关附件">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :limit="5"
              :before-upload="handleUploadBefore"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">发布</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//编辑器

import editor from "@/views/common/WangEditor/index.vue";
import { WorkerNotifyEditForm, WorkerNotify } from "@/api/notify/types";
import { addWorkerNotify, editWorkerNotify, getWorkerNotifyById } from "@/api/notify/index";

import { MessageParamsWithType, ElForm, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useScreen } from "@/store/modules/screen";

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);

const fileList = ref<UploadUserFile[]>([]);
const screenWidth = ref(600);
const itemSpan = ref(24);
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "",
      id: 0,
    }),
  },
});

const emit = defineEmits(["sendClose"]);
const loading = ref(false);
let visible = ref(props.dialogAddOrEdit.visible);
const addFormRef = ref(ElForm);
const formData = reactive<WorkerNotifyEditForm>({
  attachmentIds: [],
  id: "",
});
const dialogAddOrEdit = ref(props.dialogAddOrEdit);
console.log("初始化dialogAddOrEdit:");
console.log(dialogAddOrEdit);

const rules = reactive<FormRules<WorkerNotifyEditForm>>({
  content: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
  } else {
    screenWidth.value = 1000;
  }
}

onMounted(async () => {
  initScreen();
  loadData();
});

const loadData = async () => {
  if (dialogAddOrEdit.value.id == 0) {
    loading.value = true;
    const res = await getWorkerNotifyById(props.dialogAddOrEdit.id);
    if (res.type === 0) {
      if (res.success) {
        formData.id = res.data.id;
        console.log("新增通知返回数据,res.data:");
        console.log(res.data);
        console.log("formData:");
        console.log(formData);
      } else {
      }
    } else {
    }
    loading.value = false;
    return;
  }
  loading.value = true;
  const res = await getWorkerNotifyById(props.dialogAddOrEdit.id);
  if (res.type === 0) {
    if (res.success) {
      console.log("编辑通知返回数据,res.data:");
      console.log(res.data);
      formData.id = res.data.id;
      formData.title = res.data.title;
      formData.content = res.data.content;
      if (res.data.attachments) {
        res.data.attachments?.forEach((item: any) => {
          fileList.value.push({
            name: item.friendlyName,
            url: item.objectFilePath,
            status: "success",
            uid: item.id,
          });
        });
      }
    } else {
    }
  } else {
  }
  loading.value = false;
};

//上传相关
const handleUploadBefore = (file: any) => {
  //这里做限制上传文件的处理
  // return new Promise((resolve, reject) => {
  //   const isJPG = file.type === "image/jpeg";
  //   const isPNG = file.type === "image/png";
  //   const isGIF = file.type === "image/gif";
  //   const isBMP = file.type === "image/bmp";
  //   if (!isJPG && !isPNG && !isGIF && !isBMP) {
  //     ElMessage.error("只能上传jpg、png、gif、bmp格式的图片");
  //     return false;
  //   }
  //   const isLt2M = file.size / 1024 / 1024 < 2;
  //   if (!isLt2M) {
  //     ElMessage.error("图片大小不能超过2MB");
  //     return false;
  //   }
  //   resolve(true);
  // });
};

const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};

const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};

const handleUploadSuccess = (response: any) => {
  console.log(response);
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

/**
 * 关闭弹窗
 */
function closeDialog() {
  visible.value = false;
  emit("sendClose", "add", true);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addFormRef.value.resetFields();
  addFormRef.value.clearValidate();
  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = dialogAddOrEdit.value.id;
      if (fileList.value.length > 0) {
        formData.attachmentIds = fileList.value.map((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              return item.response.data;
            } else {
              return item.uid;
            }
          }
        });
      }
      if (id) {
        formData.id = id;
        //原型图无修改逻辑不做修改处理
        editWorkerNotify(formData)
          .then((response) => {
            if (response.type === 0) {
              if (response.success) {
                closeDialog();
              } else {
                ElMessage.error(response.msg);
              }
            } else {
              ElMessage.error(response.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        addWorkerNotify(formData)
          .then((response) => {
            if (response.type === 0) {
              if (response.success) {
                closeDialog();
              } else {
                ElMessage.error(response.msg);
              }
            } else {
              ElMessage.error(response.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style scoped>
:deep().el-upload-list {
  width: 250px;
}
</style>
